<?php defined('SYSPATH') or die('No direct script access.');
/**
 * 管理员管理
 *
 * @author  Yellow.Chow <aultoale@gmail.com>
 * @version $Id: manager.php 285 2012-06-29 02:36:31Z yellow.chow $
 * @license http://www.gnu.org/licenses/gpl-3.0.html    GPL 3
 */
class Controller_Admin_Manager extends Controller_Admin_Base
{

    /**
     * 管理员列表
     */
    public function action_index()
    {
        $this->view->managers = Model::factory('manager')->all();
    }

    /**
     * 添加管理员
     */
    public function action_add()
    {
        $model = Model::factory('manager');

        if ($this->request->is_post())
        {
            if ( ! $model->add($this->request->post('account'), (int) $this->request->post('role_id')))
            {
                $this->view->errors = $model->errors('admin.manager');
            }
            $this->render('admin/common/message');
        }

        $this->view->roles = Model::factory('manager_role')->all();
    }

    /**
     * 编辑管理员
     */
    public function action_edit()
    {
        $member_id = $this->request->param('id');
        $model = Model::factory('manager');

        $manager = $model->get('member_id', $member_id);

        if ( ! ($manager AND $manager['role_id']))
        {
            $this->message('admin.manager.not_found')
                ->link(URL::site('admin/manager'), 'admin.manager.index_url')
                ->render();
        }

        if ($this->request->is_post())
        {
            if ( ! $model->edit($member_id, $this->request->post()))
            {
                $this->view->errors = $model->errors('admin.manager');
            }
            $this->render('admin/common/message');
        }

        $this->view->set($manager);
        $this->view->roles = Model::factory('manager_role')->all();
    }

    /**
     * 删除管理员
     */
    public function action_del()
    {
        $member_id = $this->request->param('id');
        $model = Model::factory('manager');

        if ( ! $model->del($member_id))
        {
            $this->view->errors = $model->errors('admin.manager');
        }

        $this->render('admin/common/message');
    }

    /**
     * 提示会员邮箱或昵称
     */
    public function action_suggest()
    {
        $this->auto_render = FALSE;
        $founds = array();
        $rows = Model::factory('manager')->find_likes($this->request->post('value'));
        foreach ($rows as $row)
        {
            $founds[] = array(
                'value' => $row['nickname'].' <'.$row['email'].'>',
                'display' => $row['nickname'].' &lt;'.$row['email'].'&gt;',
            );
        }
        echo JSON::encode($founds, TRUE);
    }

}
